package org.jeefb.freemarker.tags;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModelException;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.jeefb.common.ServiceResult;
import org.jeefb.modules.sys.contants.SystemCachedContants;
import org.jeefb.modules.sys.service.CachedService;
import org.jeefb.modules.sys.vo.OperationVO;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;

public abstract class PermissionTag extends SecureTag {
	@Autowired
	private CachedService cachedService;

	String getName(Map params) {
		return getParam(params, "name");
	}

	protected void verifyParameters(Map params) throws TemplateModelException {
		String permission = getName(params);

		if (permission == null || permission.length() == 0) {
			throw new TemplateModelException("The 'name' tag attribute must be set.");
		}
	}

	public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException {
		String p = getName(params);
		boolean show = showTagBody(p);
		if (show) {
			renderBody(env, body);
		}
	}

	protected boolean isPermitted(String p) {
		ServiceResult<String> result = cachedService
				.getCachedObjectByKey(SystemCachedContants.ADMIN_OPERATION_SESSION + getSessionId());
		if (result.getSuccess() && result.getResult() != null) {
			List<OperationVO> list = JSON.parseArray(result.getResult(), OperationVO.class);
			for (OperationVO operationVO : list) {
				if (p.equals(operationVO.getOperateCode())) {
					return true;
				}
			}
		}
		return false;

	}

	protected abstract boolean showTagBody(String p);
}
